<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('商品库')"/>
    <th:block th:include="include :: businessCSS"/>
    <style>
        .main-content {
            position: relative;
        }

        .topbtns {
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 9999;
            background-color: #fff;
        }

        .preservationBtn {
            padding: 10px;
            margin: 0;
            position: fixed;
            top: 0;
            z-index: 9999;
            background: #fff;
            width: 100%;
        }

        .preservationBtn input {
            font-size: 16px;
            background-color: rgb(80, 138, 238);
            color: #fff;
            border: none;
            padding: 5px 30px;
            border-radius: 5px;
            cursor: pointer;
        }

        /* .layui-border-box{height: 350px !important;}
        .layui-table-body{height: 240px !important;} */
        .layui-table-tool-temp {
            padding-right: 30px;
        }

        .getDetailUpload, .getDetailUpload2 {
            cursor: pointer;
        }

        .layui-table-tool-self {
            display: none;
        }

        textarea {
            width: 98%;
            border-color: #ddd;
            padding: 8px 10px;
        }

    </style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
    <div class="main-content">
        <form class="layui-form head-form">         
		<div class="topbtns">
                <th:block th:include="include :: business_btn"/>
            </div>
            <div class="north" style="background-color: #fff;margin-top: 55px;">
                <div class="forminput"></div>
            </div>
            <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
            <div>
                <table class="layui-hide" id="dhtable" lay-filter="dhtable"></table>
                <script type="text/html" id="barDh">
                    <button class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove"
                            th:disabled="${enableEdit} == 1 ?false:true" lay-event="del">&nbsp;删除
                    </button>
                </script>
                <script type="text/html" id="zjtoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div style="font-weight: 700;font-size: 18px;">列表</div>
                        <div>
                            <button class="layui-btn layui-btn-normal dhicon"
                                    th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button"
                                    th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增	
                            </button>
                            <button class="layui-btn layui-btn-normal dhicon"
                                    th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button"
                                    th:disabled="${enableEdit} == 1 ?false:true" lay-event="batchEditArea" id="btn-sh">批量填写调入货区	
                            </button>
                            <!-- 
							<button class="layui-btn layui-btn-normal dhicon"
                                    th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button"
									th:disabled="${enableEdit} == 1 ?false:true" lay-event="importbtn" id="btn-sh">导入
                            </button>
							<button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>
							-->
                        </div>
                    </div>
                </script>
            </div>

            <th:block th:include="include :: pageFooter"/>
        </form>
    </div>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: businessJS"/>
<th:block th:include="include :: inlineJS"/>
<!-- 模板导入区域 -->
	<script id="importTpl" type="text/template" th:if="${moduleTable} ne 'TP_STOCKTAKEDOWN'">
		<form enctype="multipart/form-data" class="mt20 mb10">
			<div class="col-xs-offset-1">
				<input type="file" id="file" name="file"/>
				<div class="mt10 pt5">
					<p th:utext="'<a onclick=&quot;$.tablelist.importTemplate(\'/'+${moduleUrl}+'/exporttemplate\')&quot; class=\'btn btn-default btn-xs\'><i class=\'dhicon dh-file-excel-o\'></i> 下载模板</a>'" th:remove="tag"><p>
				</div>
				<div th:if="${buttonState['importbtn']} neq 'hidden'"
				 th:class="${buttonState['importbtn']} eq 'enable'?'layui-btn layui-table-tools importbtn-bg':'layui-btn layui-table-tools layui-btn-disabled'"
				 th:lay-event="${buttonState['importbtn']} eq 'enable'?'importBtn':''">
				<i class="dhicon dh-zu4499_1"></i> 导入
			</div>
				<font color="red" class="pull-left mt10">提示：仅允许导入“xls”或“xlsx”格式文件！</font>
			</div>
		</form>
	</script>
	

<script th:inline="javascript">
    /*<![CDATA[*/
    var prefix = ctx + "storage/manualassembly",
        prefix2 = ctx + "base/company";
    var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
    var fieldsHiddenList = [[${fieldsHiddenList}]];
    var moduleTable = [[${moduleTable}]];
    var enableEdit = [[${enableEdit}]];
    //母件表格基础信息
    var gridColumns = [[${gridColumns}]];
    var $, layer, form, table, nid, noTable;

    layui.use(['laydate', 'form', 'layer', 'jquery', 'util', 'element', 'upload', 'table'], function () {
        $ = layui.$, layer = layui.layer, form = layui.form, laydate = layui.laydate, util = layui.util, element = layui.element, upload = layui.upload, table = layui.table;
        beforeInit();//表单初始化之前的动作集合
        //初始化操作
        headcom3()
        nid = $('#nid').val()
        var listData1 = [];
        $.get("/storage/subinvtransfer/listbynid?nid=" + nid, function (data) {
            listData1 = data.data
            // 初始化表格
            $.tablelist.init({
                elem: '#dhtable'
                , data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumns.totalRow
                , cols: [gridColumns.gridBody]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '450'
                , done: function (res, curr, count) {
                    listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
                }, success: function (a, b, c) {
                    // console.log(a, b, c, 9999)
                }
            });
        });

        //监听行事件
        table.on('tool(dhtable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData1 = table.cache.dhtable;
                    for (var i = 0; i < listData1.length; i++) if (!listData1[i] || listData1[i].length == 0) listData1.splice(i, 1);//删除一项
                    table.reload('dhtable', {data: listData1});
                    break;
            }
        });
        table.on('tool(dhtable)', function (obj,tableId, importFields, listData, moduleTable, decimalObj) {
        	var wb;//读取完成的数据
        	var rABS = false; //是否将文件读取为二进制字符串
        	var iid;
        	if(!!listData.length)iid=Number(listData[listData.length-1]['iid']);else iid=1;
        	if(!obj.files) {
        		return;
        	}
        	const IMPORTFILE_MAXSIZE = 1*2048;       //这里可以自定义控制导入文件大小
        	var suffix = obj.files[0].name.split(".").slice(-1);
        	if(suffix != 'xls' && suffix !='xlsx'){
        		layer.msg('导入的文件格式不正确!')
        		return
        	}
        	if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
        		layer.msg('导入的表格文件不能大于2M')
        		return
        	}
        	showloadings(true);
        	var f = obj.files[0];
        	var reader = new FileReader();
        	reader.onload = function(e) {
        		var data = e.target.result;
        		if(rABS) {
        			wb = XLSX.read(btoa(fixdata(data)), {     //手动转化
        				type: 'base64'
        			});
        		} else {
        			wb = XLSX.read(data, {
        				type: 'binary',
        				cellDates: true,  //把时间格式数据格式化
        				dateNF: 'yyyy-MM-dd'
        			});
        		}
        		var strForm=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        		for(var i=0; i<strForm.length; i++){
        			var trData = {};
        			$.each(gridColumns.gridNewLine,function(gi,gv){trData[gi]=gv;})//逐个添加，防止污染新增模板
        			trData['iid'] = listData.length?(Number(listData.slice(-1)[0]['iid'])+1):1;
        			$.each(importFields,function(j,v){//填充存在的数值,导入字段部分带必填*,导入模板可能不带
        				var hasValue = strForm[i][j.replace("*", "")] || strForm[i][j];
        				trData[v] = hasValue ? hasValue.replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "") : '';//导入模板必填字段存在‘*’,并去除两端空格以及回车
        				if(typeof decimalObj !== 'undefined' && v in decimalObj)trData[v] = trData[v].replace(',','');//数值类型去除千分位的'，'
        				if(v.indexOf("d") == 0){//字段名d开头为日期字段，需替换符号
        					trData[v] = trData[v].replace(/\//g,"-");
        				}
        			})
        			if(['TP_STOCKOFFERPRICE','TP_STOCKBARGAININ','TP_STOCKBARGAININDETAIL'].includes(moduleTable)){//销售报价、销售合同、合同清单新增
        				trData.gIDC = trData.gIDC || trData.gID;//客户型号
        				trData.gNameC = trData.gNameC || trData.gName;//客户品名
        				trData.vWlBhC = trData.vWlBhC || trData.vWlBh;//客户物料编号
        				trData['bPrice'] = trData['bPrice'] ? Number(trData['bPrice']).toFixed(decimalObj.bPrice) : 0;
        				trData['bNumb'] = trData['bNumb'] ? Number(trData['bNumb']).toFixed(decimalObj.bNumb) : 0;
        			}
        			listData.push(trData);
        		}
        		listData = calcDetail(listData);//导入数据资金计算
        		table.reload(tableId,{data:listData});
        	};
        	if(rABS) {
        		reader.readAsArrayBuffer(f);
        	} else {
        		reader.readAsBinaryString(f);
        	}

        	return true;
        }
        );
        //头工具栏事件
        table.on('toolbar(dhtable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
        			var title = '选择库存',url = "/storage/stockcontrol/select?pagetype=checkbox&checkwsx1=1";
        			layer.open({
        				type: 2//Page层类型
        				,area: ['1000px', '700px']
        				,offset: '10%'
        				,title: title
        				,shade: 0.6 //遮罩透明度
        				,maxmin: true //允许全屏最小化
        				,content: url
        				,btn: ['确定', '关闭'] //只是为了演示
        				,yes: function(index){
        					var res = window["layui-layer-iframe" + index].callbackdata(11);
        					console.log('res---', res);
        					if(res.length > 0){
    							$.each(res,function (i,v) {
    								v['toGoodsAllocation'] = '';
    								v['goodsAllocation'] = v['vHw'];
    								v['goodsArea'] = v['vKq'];
    								v['warehouseAddress'] = v['gDepot'];
    								v['allotNum'] = v['productNum'];
    								
    								// 是否已存在
    								var isExist = false;
    								for(var j = 0; j < listData1.length; j++) {
    									if(listData1[j]['guid'] == v['guid']) {
    										isExist = true;
    									}
    								}
    								if(isExist == false) {
        								listData1.push(v);
    								}
    							})
        						table.reload('dhtable', {data: listData1});
        						layer.closeAll();
        					}else{
        						layer.msg("请选择数据");
        					}
        				}
        				,btn2: function(){
        					layer.closeAll();
        				}
        			});
                    break;
                case 'batchEditArea':
        			var title = '选择货区',url = "/storage/goodsallocation/select?deleted=0&pagetype=radio";
        			layer.open({
        				type: 2//Page层类型
        				,area: ['1000px', '700px']
        				,offset: '10%'
        				,title: title
        				,shade: 0.6 //遮罩透明度
        				,maxmin: true //允许全屏最小化
        				,content: url
        				,btn: ['确定', '关闭'] //只是为了演示
        				,yes: function(index){
        					var res = window["layui-layer-iframe" + index].callbackdata();
        					console.log('res---', res);
        					if(res){
    							$.each(listData1,function (i,v) {
    								v['toGoodsAllocation'] = res['goodsAllocation'];
    								v['toGoodsArea'] = res['goodsArea'];
    								v['toWarehouseAddress'] = res['warehouseAddress'];
    							})
        						table.reload('dhtable', {data: listData1});
        						layer.closeAll();
        					}else{
        						layer.msg("请选择数据");
        					}
        				}
        				,btn2: function(){
        					layer.closeAll();
        				}
        			});
                    break;
                case 'importbtn':
    				$.tablelist.importExcel('dhtable',importFields, table.cache.dhtable, moduleTable, decimalObj);
    				break;
                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            }
            ;
        });
		

        //监听单元格编辑
        table.on('edit(dhtable)', function (obj) {
            // var tr = obj.tr;
            // // 单元格编辑之前的值
            // var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
            // console.log("oldtext",oldtext)
            listData1.map((n, m) => {
                if (n.allotNum > n.productNum) {
                    n.allotNum = n.productNum
                    layer.msg("移仓数量不可超过商品数量!")
                    return
                }
            })
            table.reload('dhtable', {data: listData1});
        });

        $(".fieldsimg").each(function () {
            var id = $(this).attr('name')
            upload.render({
                elem: '#' + id + '_upimg',
                url: '/system/fileinfo/uploadmailimg',
                accept: 'images',
                before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        console.log(index, file, result)
                    });
                },
                done: function (res) {
                    //如果上传失败
                    if (res.errno > 0) {
                        return layer.msg('上传失败');
                    } else {
                        layer.msg('上传成功');
                        $('#' + id).val(res.data[0])
                        layui.$('#' + id + '_upimg').find('.upicon').addClass('layui-hide')
                        layui.$('#' + id + '_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data[0]);
                    }
                }, error: function (err) {
                    //演示失败状态，并实现重传
                    console.log(err)
                }
            });
        })


        $('.t_date').each(function () {
            var datetype = $(this).attr('datetype')
            laydate.render({
                elem: this
                ,
                type: datetype == 't_date' ? 'date' : datetype == 't_datetime' ? 'datetime' : datetype == 't_year' ? 'year' : 'month'
            })
        })
		    
});


</script>

</body>
</html>